package cn.icyzx.controller;

import cn.icyzx.models.Comment;
import cn.icyzx.models.Tag;
import cn.icyzx.models.User;
import cn.icyzx.models.Work;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;
import cn.icyzx.service.LoginService;
import net.sf.json.JSONObject;
import cn.icyzx.service.TagService;
import cn.icyzx.service.WorkService;
import cn.icyzx.util.CommonUtil;

import static cn.icyzx.util.WorksSelectCondition.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.*;

import static cn.icyzx.util.CommonUtil.conditionToUrl;
import static cn.icyzx.util.StaticConstUtil.*;

/**
 * Created by 郑凯 on 2016/8/29.
 */
@Controller
public class WorkProcess {

    private static Logger logger = Logger.getLogger(WorkProcess.class);

    @Autowired
    public LoginService loginService;

    @Autowired
    WorkService workService;

    @Autowired
    TagService tagService;

    @RequestMapping("/workInfo/{wid}")
    public ModelAndView worksInfo(@PathVariable String wid, HttpSession session,
                                  ModelAndView modelAndView) {
        Work work = workService.getWorkByWid(wid);
        if (work == null) {
            modelAndView = new ModelAndView("/login");
            modelAndView.addObject("loginTip", "不存在的错误");
            return modelAndView;
        } else {
            modelAndView = new ModelAndView("workInfo");
            workService.over(wid);
            List<Comment> listComments = workService.getlistCommentsByWid(wid);
            Map workOperateStatus;

            if (session.getAttribute("user") != null) {
                User user = (User) session.getAttribute("user");
                workOperateStatus = workService.getWorkOperateStatus(wid, user.getUid());  // 暂时包含了用户推荐和收藏的状态
            } else
                workOperateStatus = null;

            modelAndView.addObject("workOperateStatus", workOperateStatus);
            modelAndView.addObject("work", work);
            modelAndView.addObject("listComments", listComments);
            return modelAndView;
        }
    }

    @RequestMapping(value = "/work/operate", method = RequestMethod.POST, produces = "test/html;charset=utf-8")
    @ResponseBody
    String operateWork(@RequestParam("wid") String wid, @RequestParam("type") String type, HttpSession httpSession) {
        if (httpSession.getAttribute("user") == null) return LOGIN_NECESSARY;
        else {
            User user = (User) httpSession.getAttribute("user");
            if (workService.addWorkOperate(wid, user.getUid(), type)) return STATUS_SUCCESS;
            else return STATUS_FAIL;
        }
    }


    /**
     * worksShow 不带页码，转发到一般请求
     *
     * @param modelAndView
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = "/work/show", method = RequestMethod.GET)
    public ModelAndView worksShow(ModelAndView modelAndView) throws Exception {
        return new ModelAndView("forward:/work/show/1");
    }

    /**
     * worksShow 根据输入的几个独立条件，组装查询条件，返回结果集
     *
     * @param curPage
     * @param request
     * @param modelAndView
     * @return org.springframework.web.servlet.ModelAndView
     */
    @RequestMapping(value = "/work/show/{curPage}", method = RequestMethod.GET)
    public ModelAndView worksShow(@PathVariable String curPage, HttpServletRequest request,
                                  ModelAndView modelAndView) throws Exception {
        final String orderBy = request.getParameter(ORDERBY);
        final String year = request.getParameter(YEAR);
        final String key = request.getParameter(KEY);
        final String show_active; //正在活动的排序

        Map<String, String> condition = new HashMap<String, String>();
        condition.put(YEAR, year);
        condition.put(KEY, key);
        condition.put("curPage", curPage);

        List<Work> listWorks = workService.getlistWorks(condition);

        if (orderBy != null) {
            switch (orderBy) {
                case "collection":
                    Collections.sort(listWorks, new CommonUtil.WorkOderByCollectionComparator());
                    show_active = COLLECTION;
                    break;
                case "recommend":
                    Collections.sort(listWorks, new CommonUtil.WorkOderByRecommendComparator());
                    show_active = RECOMMEND;
                    break;
                case "over":
                    Collections.sort(listWorks, new CommonUtil.WorkOderByOverComparator());
                    show_active = OVER;
                    break;
                default:
                    show_active = NEW;
                    logger.error("排序顺序错误");
            }
        } else show_active = NEW;

        JSONObject page = new JSONObject();
        int sumPage = workService.getWorksPageSum(condition);
        page.put("sumPage", Integer.valueOf(sumPage));
        page.put("curPage", Integer.valueOf(curPage));
        page.put("condition", conditionToUrl(condition));

        List<Tag> hotTagList = tagService.getHotTagList();
        List<Work> hotWorkList = workService.getHotWork();

        modelAndView = new ModelAndView("worksShow");
        modelAndView.addObject("hotWorkList", hotWorkList);
        modelAndView.addObject("hotTagList", hotTagList);//热门标签
        modelAndView.addObject("listWorks", listWorks);
        modelAndView.addObject("page", page);
        modelAndView.addObject("show_active", show_active);//识别筛选条件导航栏
        modelAndView.addObject("active", WORKSHOW); //识别main导航栏

        logger.info("condition:" + condition.toString());
        return modelAndView;
    }

    @RequestMapping(value = "/work/publish", method = RequestMethod.GET)
    public ModelAndView workPublish(ModelAndView modelAndView) {
        modelAndView = new ModelAndView("work-publish");
        return modelAndView;
    }

    @RequestMapping(value = "/work/publish", method = RequestMethod.POST)
    @ResponseBody
    String workPublish(@RequestParam("title") String title, @RequestParam("content") String content,
                       @RequestParam("tags[]") String[] tags, HttpServletRequest request) {

        User user = (User) request.getSession().getAttribute("user");
        String uid = user.getUid();
        JSONObject jsonWork = new JSONObject();
        jsonWork.put("title", title);
        jsonWork.put("content", content);
        jsonWork.put("tags", tags);
        jsonWork.put("uid", uid);
        workService.insertWork(jsonWork);

        return STATUS_SUCCESS;
    }

    @RequestMapping(value = "/work/addComment", method = RequestMethod.GET, produces = "text/html;charset=utf-8")
    @ResponseBody
    String addComment(HttpServletRequest request) {
        User user = (User) request.getSession().getAttribute("user");

        String wid = (String) request.getParameter("wid");
        String uid = user.getUid();
        String info = (String) request.getParameter("info");

        System.out.println(wid + info);
        try {
            workService.commentWork(wid, uid, info);
            return STATUS_SUCCESS;
        } catch (Exception e) {
            logger.error("添加评论失败");
            return STATUS_FAIL;
        }

    }

}
